package com.liuke.question3;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.io.*;
import java.text.Collator;
import java.util.*;

/**
 * @Auther: 刘科
 * @Date: 2021/06/29/11:42
 * @Description:
 */
public class Question {
    private static String FILENAME_PROP = "sdxl_prop.txt";

    private static List<String> natureOrder;
    private  Map<String, String> indexOrder;
    private List<String> charOrder;
    private List<String> charOrderDESC;
    /**
     * 分析
     */
    public void analyse() {
        getOrderList();
        writeResultFile();

    }

    private void getOrderList() {
        //natureOrder
        natureOrder = natureOrderFunction();
        //indexOrder
        indexOrder = indexOrderFunction();

        //charOrder
        charOrder = Lists.newCopyOnWriteArrayList(natureOrder);
        charOrder.sort(Comparator.naturalOrder());
        //charOrderDESC

        charOrderDESC = Lists.newCopyOnWriteArrayList(natureOrder);
        charOrderDESC.sort(Comparator.reverseOrder());
    }

    /**
     * 分析并写入到sdxl.txt文件中
     */
    private void writeResultFile() {
        InputStreamReader read = null;
        String FILENAME_TEMPLATE = "sdxl_template.txt";
        String filePath = Objects.requireNonNull(Question.class.getClassLoader().getResource(FILENAME_TEMPLATE)).getPath();
        File fileRead = new File(filePath);
        OutputStreamWriter out = null;
        String WRITE_FILE = "sdxl.txt";
        File fileWrite = new File("D:\\graduationPreject\\homework\\src\\main\\resources\\" + WRITE_FILE);
        try {
            read = new InputStreamReader(new FileInputStream(fileRead));
            out = new OutputStreamWriter(new FileOutputStream(fileWrite));
            if (fileRead.isFile() && fileRead.exists()) {
                BufferedReader bufferedReader = new BufferedReader(read);
                BufferedWriter bufferedWriter = new BufferedWriter(out);
                String txt = null;
                while ((txt = bufferedReader.readLine()) != null) {
                    String analyseStr = analyseRow(txt);
                    bufferedWriter.write(analyseStr);
                    bufferedWriter.newLine();
                }
            } else {
                throw new Exception("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 按行分析，截取出需要替换的函数和索引
     * @param txt
     * @return
     */
    private String analyseRow(String txt) {
        StringBuilder resultStr = new StringBuilder();
        //函数名字
        String functionName = null;
        int nameStart = 0;
        int nameEnd = 0;
        while (nameStart < txt.length()) {
            //将不是$开头的先拼接到resultStr中
            if (txt.charAt(nameStart) != '$') {
                resultStr.append(txt.charAt(nameStart));
                nameStart++;
                continue;
            }
            //找到$开头后，将解析这个函数
            //使用nameEnd找到'('
            nameEnd = nameStart;
            while (nameEnd < txt.length()) {
                if (txt.charAt(nameEnd) != '(') {
                    nameEnd++;
                    continue;
                }
                //找到将函数名字赋值到functionName变量中
                nameStart++;
                functionName = txt.substring(nameStart, nameEnd);
                //继续找index索引
                nameStart = nameEnd + 1;
                while (nameEnd < txt.length()) {
                    if (txt.charAt(nameEnd) != ')') {
                        nameEnd++;
                        continue;
                    }
                    //找到索引
                    String functionIndex = txt.substring(nameStart, nameEnd);
                    resultStr.append(selectFunctionSelect(functionName, functionIndex));
                    break;
                }
                break;
            }
            nameStart = nameEnd + 1;
        }

        return resultStr.toString();
    }

    private String selectFunctionSelect(String functionName, String functionIndex) {
        switch (functionName) {
            case "natureOrder":
                return natureOrder.get(Integer.parseInt(functionIndex));
            case "indexOrder":
                return indexOrder.get(functionIndex);
            case "charOrder":
                return charOrder.get(Integer.parseInt(functionIndex));
            case "charOrderDESC":
                return charOrderDESC.get(Integer.parseInt(functionIndex));
            default:
                return null;
        }
    }

    private Map<String, String> indexOrderFunction() {
        InputStreamReader read = null;
        Map<String, String> mapResult = Maps.newHashMap();
        String filePath = com.liuke.question3.Question.class.getClassLoader().getResource(FILENAME_PROP).getPath();
        File file = new File(filePath);
        try {
            read = new InputStreamReader(new FileInputStream(file));
            if (file.isFile() && file.exists()) {
                BufferedReader bufferedReader = new BufferedReader(read);
                String txt = null;
                while ((txt = bufferedReader.readLine()) != null) {
                    String[] split = txt.split("\t");
                    mapResult.put(split[0].trim(), split[1].trim());
                }
            } else {
                throw new Exception("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return mapResult;
    }

    /**
     * natureOrder
     */

    private List<String> natureOrderFunction() {
        InputStreamReader read = null;
        List<String> natureOrder = Lists.newArrayList();
        String filePath = com.liuke.question3.Question.class.getClassLoader().getResource(FILENAME_PROP).getPath();
        File file = new File(filePath);
        try {
            read = new InputStreamReader(new FileInputStream(file));
            if (file.isFile() && file.exists()) {
                BufferedReader bufferedReader = new BufferedReader(read);
                String txt = null;
                while ((txt = bufferedReader.readLine()) != null) {
                    natureOrder.add(txt.split("\t")[1].trim());
                }
            } else {
                throw new Exception("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return natureOrder;
    }

}
